package com.niiwoo.civet.trade.service.local.contract;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.dto.response.UserAuthorizationInfoResponseDTO;
import com.niiwoo.civet.user.dto.response.UserIdentityInfoResponseDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.civet.user.service.UserAuthorizationInfoDubboService;
import com.niiwoo.civet.user.service.UserIdentityDubboService;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO.DynamicTable;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 委托授权协议
 * @author liaojunjun
 */
@Service
public class ConsignorAuthorizeProtocol extends AbstractFadadaContract {

    private static final Logger logger = LoggerFactory.getLogger(ConsignorAuthorizeProtocol.class);

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Reference(version = "1.0.0")
    private UserIdentityDubboService userIdentityDubboService;
    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;

    @Reference(version = "1.0.0")
    private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;

    @Value("${platform.caCertId}")
    private String platformCaCertId;
 

    @Override
    public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                           Project project, String userId) throws Exception {
        logger.info("委托授权协议处理开始... userId:{}", userId);

        UserIdentityInfoResponseDTO consignor = userIdentityDubboService.get(userId);
        if(Objects.isNull(consignor)) {
        	consignor = new UserIdentityInfoResponseDTO();
        	consignor.setUserId(userId);
        	SimpleOrgInfo orgInfo = organizationDubboService.getByOrgId(userId);
        	if(Objects.isNull(orgInfo)) {
        		throw new RuntimeException("授权委托协议失败，用户ID找不到个人信息和机构信息"+userId); 
        	}
        	consignor.setName(orgInfo.getOrganizationName());
        	String idCard = null;
			 if((idCard = orgInfo.getUnifiedSocialCreditCode()) == null && (idCard = orgInfo.getCharterCode()) == null ) {
				 throw new RuntimeException("授权委托协议失败，统一信用代码和营业编号为空,机构ID"+userId); 
			 }
			consignor.setIdCard(idCard);
			consignor.setCaCertId(orgInfo.getFadadaCacertId());
        }else {
        	UserAuthorizationInfoResponseDTO authorizationInfoResponseDTO = userAuthorizationInfoDubboService.getUserAuthorizationInfo(consignor.getUserId());
        	consignor.setCaCertId(authorizationInfoResponseDTO.getFadadaCacertId());
        }
        this.generateContract(contractTemplate, bizContractNo, consignor);

        ProjectContract result = this.signContract(contractTemplate, bizContractNo, userId, consignor);

        this.contractFilling(bizContractNo);
        logger.info("委托授权协议处理结束... userId:{}", userId);
        return result;

    }

    private void generateContract(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                  UserIdentityInfoResponseDTO consignor) throws Exception {
        logger.info("委托授权协议生成开始...");
        GenerateContractRequestDTO dto = new GenerateContractRequestDTO();

        dto.setContractId(bizContractNo);   //合同编号
        dto.setDocTitle(contractTemplate.getTemplateName());
        dto.setTemplateId(contractTemplate.getTemplateId());

        Map<String, String> parameterMap = new HashMap<String, String>();

        parameterMap.put("consignor", consignor.getName());
        parameterMap.put("idCard", consignor.getIdCard());

        parameterMap.put("signDate", DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));

        dto.setParameterMap(parameterMap);

        // 签章列表
        List<List<String>> signatureNamesList = new ArrayList<>();

        // 签章信息
        String antiGuaranteeSignatureNamesText = "                委托方：" + consignor.getName();
        List<String> antiGuaranteeSignatureNamesCells = new ArrayList<>();
        antiGuaranteeSignatureNamesCells.add(antiGuaranteeSignatureNamesText);
        signatureNamesList.add(antiGuaranteeSignatureNamesCells);

        // 签章信息
        String guaranteeSignatureNamesText = "                受托方：深圳市你我金融信息服务有限公司";
        List<String> guaranteeSignatureNamesCells = new ArrayList<>();
        guaranteeSignatureNamesCells.add(guaranteeSignatureNamesText);
        signatureNamesList.add(guaranteeSignatureNamesCells);

        List<String> headers = new ArrayList<>();
        headers.add("");
        // 所有人签名 在pdf合同模板的keyword下面插入(正好在页尾，不用留空白)，需要留够空白，不然会覆盖下面的内容
        DynamicTable signNameTable = new DynamicTable();
        signNameTable.setInsertWay(1);
        signNameTable.setKeyword("一切与乙方无关。");
        signNameTable.setCellHeight(60f);
        signNameTable.setHeaders(headers);
        // 签名时需要增加高度并居中显示
        signNameTable.setCellVerticalAlignment(5);
        signNameTable.setDatas(signatureNamesList);
        signNameTable.setBorderFlag(false);
        List<DynamicTable> tables = new ArrayList<DynamicTable>();
        tables.add(signNameTable);

        dto.setDynamicTables(tables);

        generateContract(dto);
        logger.info("委托授权协议生成结束...");
    }

    private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, String contractId, String userId, UserIdentityInfoResponseDTO consignor) throws Exception {
        String METHOD_NAME = "法大大合同自动签署-委托授权协议 userId:" + userId;
        logger.info(METHOD_NAME);
        String docTitle = consignor.getName() + "的委托授权协议_" + contractId;

        // 委托方签署
        String transactionId = snowflakeIdWorker.nextId() + "";
        
        String borrowerCaCertId =consignor.getCaCertId();
        if(Objects.isNull(borrowerCaCertId)) {
        	logger.error("法大大合同自动签署-委托授权协议 失败，CA编号为空，用户{}",userId);
        	throw new RuntimeException("法大大合同自动签署-委托授权协议 失败，CA编号为空");
        }
                
        String borrowerSignKeyword = "委托方：" + consignor.getName();
        FadadaResponseDTO fadadaResponse = extSignAuto(transactionId, contractId, borrowerCaCertId,
                SignClientRoleEnum.BORROWER.getValue(), docTitle, borrowerSignKeyword);
        logger.info("法大大合同自动签署-委托授权协议 借款人签署结束... userId:{}", userId);
        // 担保公司签署
        transactionId = snowflakeIdWorker.nextId() + "";
        String guaranteeSignKeyword = "受托方：深圳市你我金融信息服务有限公司";
        fadadaResponse = extSignAuto(transactionId, contractId, platformCaCertId,
                SignClientRoleEnum.GUARANTEE.getValue(), docTitle, guaranteeSignKeyword);
        logger.info("法大大合同自动签署-委托授权协议 担保公司签署结束... userId:{}", userId);
		return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), contractId, transactionId,
				fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
    }

}
